package com.heima.user.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.WeakHashMap;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto ) {
        //1.检查参数
        dto.checkParam();
        //2.封装查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus()!=null) {
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }//3.封装分页条件
        Page<ApUserRealname> pageRe = new Page<>(dto.getPage(), dto.getSize());
        //4.执行分页查询
        IPage<ApUserRealname> pageResult = this.page(pageRe, queryWrapper);
        //5.返回封装数据
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }
    @Autowired
   private ApUserMapper apUserMapper;

    /**
     * @param dto id:realnameId msg:驳回原因
     * @param status  2 审核失败   9 审核成功
     * @return
     */
  //  @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 200000)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验参数
        //id不为空
        if (dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        //根据id查询实名认证信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (apUserRealname==null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"关联的实名认证信息不存在");
        }
        //判断认证状态是否为待审核
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态 不是待审核状态");
        }
        //查询所认证信息所关联的apUser账户
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"关联的ap用户信息不存在");
        }
        //2.修改实名认证的状态 (补全 时间  状态 原因)
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        this.updateById(apUserRealname);
        //3.判断状态是否为9
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //3.1开通自媒体账户
        WmUser wmUser= createWmUser(apUser);
            //3.2创建作者信息
            createAuthor(wmUser);
        }

        return ResponseResult.okResult();
    }
    @Autowired
    ArticleFeign articleFeign;

    private void createAuthor(WmUser wmUser) {
        //1.使用feign远程查询对应的作者信息是否存在
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if (!authorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApAuthor apAuthor = authorResult.getData();
        //2.如果不存在  创建作者信息
        if (apAuthor!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }
        apAuthor= new ApAuthor();
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(wmUser.getApUserId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());
        //3.使用feign远程保护作者信息
        ResponseResult saveResult = articleFeign.save(apAuthor);
        if (!saveResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    @Autowired
    WemediaFeign wemediaFeignl;
    /**
     * 远程调用自媒体服务,开通自媒体账户
     * @param apUser 基于qpp账户创建
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1.远程查询 自媒体账户是否已经存在
        ResponseResult<WmUser> result  = wemediaFeignl.findByName(apUser.getName());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmUser wmUser = result.getData();
        if (wmUser!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"账户已经存在");
        }
        //2.如果不存在 创建自媒体账户
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setApUserId(apUser.getId());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        //3.远程保存自媒体账户信息
        ResponseResult<WmUser> saveResult = wemediaFeignl.save(wmUser);
        if (!saveResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        return saveResult.getData();//返回保存成功的自媒体用户信息
    }
}
